package com.customization.unionpay.market.job;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.customization.unionpay.market.util.FormDataUtils;
import com.customization.unionpay.market.util.CloudFlashPaymentUtils;
import com.customization.unionpay.market.util.PropUtils;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.general.Util;
import weaver.integration.logging.Logger;
import weaver.integration.logging.LoggerFactory;
import weaver.interfaces.schedule.BaseCronJob;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * @author sjm
 * @description 定时根据授权码调用云闪付营销开放平台接口获取数据，活动是否核销为否，修改活动核销日期，活动总额，活动是否核销,活动结束日期
 */
public class SyncMarketActivityInfoByThirdJob extends BaseCronJob {

    private static final Logger log = LoggerFactory.getLogger(SyncMarketActivityInfoByThirdJob.class);

    public void execute() {

        RecordSet rs = new RecordSet();

        try {
            // 营销活动事项台账表单id
            int formId = Integer.parseInt(PropUtils.BB_LOG.getPropValue("marketSubject", "marketing_activity_ledger_form_id"));

            // 查询枚举 活动是否核销
            String selectValueNo =  com.customization.unionpay.market.util.FormDataUtils.getItemValue(formId, "hdsfhx", "否");
            log.info("活动是否核销 否："+selectValueNo);
            String selectValueYes = com.customization.unionpay.market.util.FormDataUtils.getItemValue(formId, "hdsfhx", "是");
            log.info("活动是否核销 是："+selectValueYes);
            if (StrUtil.isNotBlank(selectValueNo) && StrUtil.isNotBlank(selectValueYes)) {

                // 营销活动事项台账主表表名
                String ledgerTableName = com.customization.unionpay.market.util.FormDataUtils.getTableName(formId);
                log.info("营销活动事项台账主表表名："+ledgerTableName);
                if (StrUtil.isNotBlank(ledgerTableName)) {
                    String sql = "select id,yxpthdsqm as actAuthCode from  #{tableName} where hdsfhx = ? and yxpthdsqm is not null";
                    sql = sql.replace("#{tableName}",ledgerTableName);
                    log.info("sql:"+sql);
                    // 查询营销活动事项台账活动是否核销为否的数据
                    rs.executeQuery(sql,selectValueNo);
                    List<String> codes = new ArrayList<>();
                    // 建立对应关系
                    while (rs.next()) {
                        String actAuthCode = Util.null2String(rs.getString("actAuthCode"));
                        if (!"".equals(actAuthCode)) {
                            if (!codes.contains(actAuthCode)) {
                                codes.add(actAuthCode);
                            }
                        }
                    }

                    // 判断集合是否大于0
                    if (codes.size() > 0) {

                        List<List<String>> lists = FormDataUtils.splitList(codes, 1000);
                        // 最大请求授权码为1000
                        for (List<String> list : lists) {
                            // 云闪付请求
                            String resultStr = CloudFlashPaymentUtils.batchQueryByBudgetAuthCode(list);
                            log.info("返回参数：" + resultStr);

                            JSONObject resultJson = JSONObject.parseObject(resultStr);

                            String errorMessage = resultJson.getString("errorMessage");
                            if ("成功".equals(errorMessage)) {
                                JSONArray data = resultJson.getJSONArray("data");
                                log.info("解析data参数：" + data);
                                if(data.size() > 0){
                                    for (int i = 0; i < data.size(); i++) {
                                        JSONObject single = data.getJSONObject(i);
                                        // 授权码
                                        String code = single.getString("budgetAuthCode");
                                        log.info("code:" + code);
                                        // 活动核销日期 = 核销日期
                                        String writeOffDate = single.getString("writeOffDate");
                                        log.info("writeOffDate:" + writeOffDate);
                                        // 活动总额 = 项目充值金额
                                        String budgetValueChecked = "".equals(single.getString("budgetValueChecked")) ? "0" : single.getString("budgetValueChecked");
                                        log.info("budgetValueChecked:" + budgetValueChecked);
                                        // 活动是否核销 = 状态
                                        String stat = single.getString("stat");
                                        log.info("stat:" + stat);
                                        // 活动结束日期 = 项目结束日期
                                        String projectEndDateChecked = single.getString("projectEndDateChecked");
                                        log.info("projectEndDateChecked:" + projectEndDateChecked);
                                        // TODO 同步资金账户类型
                                        log.info("zjzhlx：" + single.getString("AcctType") );
                                        Integer zjzhlx = single.getString("AcctType") == null ? 0 : (single.getInteger("AcctType")-1);
                                        log.info("zjzhlx:" + zjzhlx);

                                        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                                        LocalDate date = LocalDate.parse(projectEndDateChecked, formatter);
                                        log.info("原日期：" + date);
                                        LocalDate newDate = date.plusDays(90); // 在指定日期上加90天
                                        log.info("在指定日期上加90天：" + newDate);
                                        String yjjqrq = newDate.format(formatter);
                                        log.info("yjjqrq：" + yjjqrq);
                                        RecordSetTrans rst = new RecordSetTrans();
                                        // 开启事务（关闭自动提交）
                                        rst.setAutoCommit(false);
                                        try {
                                            String act_is_cancel = selectValueNo;
                                            if ("5".equals(stat)) {
                                                act_is_cancel = selectValueYes;
                                            }

                                            StringBuilder updateSql = new StringBuilder("update ");
                                            updateSql.append(ledgerTableName);
                                            updateSql.append(" set hdhxrq='");
                                            updateSql.append(writeOffDate);
                                            updateSql.append("',");
                                            updateSql.append("ACT_TOTAL_AT='");
                                            updateSql.append(budgetValueChecked);
                                            updateSql.append("',");
                                            updateSql.append("hdsfhx='");
                                            updateSql.append(act_is_cancel);
                                            updateSql.append("',");
                                            updateSql.append("ACT_END_TM='");
                                            updateSql.append(projectEndDateChecked);
                                            updateSql.append("',");
                                            updateSql.append("yjjqrq='");
                                            updateSql.append(yjjqrq);
                                            updateSql.append("',");
                                            updateSql.append("zjzhlx='");
                                            updateSql.append(zjzhlx);
                                            updateSql.append("'  where yxpthdsqm = '");
                                            updateSql.append(code);
                                            updateSql.append("' ");

                                            log.info("updateSql:"+updateSql.toString());

                                            // 修改营销活动事项台账 活动核销日期，活动总额，活动是否核销,活动结束日期
                                            rst.executeUpdate(updateSql.toString());
                                            // 提交事务
                                            rst.commit();

                                        } catch (Exception e) {
                                            // 回滚
                                            rst.rollback();
                                            log.error("修改数据异常：" + e.getMessage());
                                        }
                                    }
                                }else {
                                    log.error("云闪付根据授权码查询为空！");
                                }
                            } else {
                                log.error("云闪付查询失败：" + resultJson.getString("errorCode") + "----" + resultJson.getString("errorMessage"));
                            }
                        }
                    }
                } else {
                    log.error("根据营销活动事项台账formId查询数据库表名失败！");
                }
            } else {
                log.error("活动是否核销枚举为空或找不到！");
            }
        } catch (Exception e) {
            log.error("定时任务异常：" + e.getMessage());
        }
    }
}

